package com.jd.platform.gobrs.client.gcache;

import com.jd.platform.gobrs.client.core.rule.KeyRuleHolder;
import com.jd.platform.gobrs.client.gcache.cache.DefaultMCaffeineCache;
import com.jd.platform.gobrs.client.gcache.cache.MCaffeineCacheWrapper;

/**
 * 用户可以自定义cache
 *
 * @author sizegang wrote on 2020-02-24
 * @version 1.0
 */
public class LocalCacheFactory extends AbstractLocalCacheFactory {

    private static final LocalCache DEFAULT_CACHE = new DefaultMCaffeineCache();

    /**
     * 创建一个本地缓存实例
     */
    public static LocalCache build(int duration) {
        return new MCaffeineCacheWrapper(duration);
    }

    /**
     * 从规则池中拿 已配规则的key 对应的缓存
     *
     * @param key
     * @return
     */
    @Override
    public LocalCache getNonNullCache(String key) {
        LocalCache localCache = getFromRuleCache(key);
        if (localCache == null) {
            // 没有配置规则 返回默认的缓存
            return DEFAULT_CACHE;
        }
        return localCache;
    }
    @Override
    public  LocalCache getFromRuleCache(String key) {
        // 查询当前key 是否已经在gobrs-dashboard端配置了规则
        return KeyRuleHolder.findByKey(key);
    }

}
